package cn.yto.print.socket;

import cn.hutool.json.JSONUtil;
import cn.yto.print.config.WeightLinkedContext;
import cn.yto.print.constants.AssistantConstants;
import cn.yto.print.model.response.WeightResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
@ServerEndpoint(value = "/getWeight")
public class WeightSocketEndpoint {

    @OnOpen
    public void onOpen(Session session) {
        String sessionId = UUID.randomUUID().toString();
        session.getUserProperties().put(AssistantConstants.SESSION_ID, sessionId);
        WeightLinkedContext.addSession(sessionId, session);
        WeightResponse weightResponse = new WeightResponse(2, "称重连接通道建立成功");
        sendMessage(session, JSONUtil.toJsonStr(weightResponse));
    }

    @OnMessage
    public void onMessage(String message, Session session) {
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = (String) session.getUserProperties().get(AssistantConstants.SESSION_ID);
        log.info("前端称重通道连接断开，会话ID：{}，状态码：{}，关闭原因：{}", sessionId, reason.getCloseCode(), reason.getReasonPhrase());
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (Exception e) {
            log.error("前端称重通道关闭连接发生异常", e);
        }
        WeightLinkedContext.removeSession(sessionId);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("前端称重通道连接发生异常", error);
    }

    /**
     * 发送消息
     */
    public void sendMessage(Session session, String message) {
        try {
            session.getAsyncRemote().sendText(message);
//            log.info("发送前端称重响应报文：{}", message);
        } catch (Exception e) {
//            log.error("发送前端称重响应报文异常: ", e);
        }
    }

    public void massMessage(String message) {
        Map<String, Session> sessionMap = WeightLinkedContext.getAllSession();
        if (sessionMap.size() > 0) {
            for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
                sendMessage(entry.getValue(), message);
            }
        }
    }

}
